package com.megvii.corelib.components;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.megvii.corelib.R;

/**
 * Created by linyue on 15/12/25.
 */
public class DeviceSelectView extends RelativeLayout
        implements View.OnClickListener, View.OnKeyListener
{
    protected TextView titleText;

    protected DeviceSelectListener listener;

    public DeviceSelectView(Context context)
    {
        super(context);
        init(context, null);
    }

    public DeviceSelectView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(context, attrs);
    }

    public DeviceSelectView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs)
    {
        inflate(context, R.layout.device_select_layout, this);
        titleText = (TextView) findViewById(R.id.device_select_layout_title);
        findViewById(R.id.device_select_layout_albumLinear).setOnClickListener(this);
        findViewById(R.id.device_select_layout_cameraLinear).setOnClickListener(this);
        this.setOnClickListener(this);
        this.setOnKeyListener(this);
    }

    public void setTitleText(String text)
    {
        if (text != null)
        {
            titleText.setText(text);
        }
    }

    public void setListener(DeviceSelectListener listener)
    {
        this.listener = listener;
    }


    public void onClick(View view)
    {
        if (listener != null)
        {
            int id = view.getId();
            if (id == R.id.device_select_layout_albumLinear)
            {
                listener.onChooseDevice(Device.ALBUM);
            }
            else if (id == R.id.device_select_layout_cameraLinear)
            {
                listener.onChooseDevice(Device.CAMERA);
            }
            else if (id == this.getId())
            {
                listener.onCancel();
            }
        }
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if (listener != null)
        {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
            {
                listener.onCancel();
                return true;
            }
        }
        return false;
    }

    public enum Device
    {
        ALBUM,
        CAMERA
    }

    public interface DeviceSelectListener
    {
        public void onChooseDevice(Device device);

        public void onCancel();
    }
}
